package com.djx.redis.bean;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;


/**
 * redis集成Bean
 * @author dingjunxiong
 */
@Configuration
public class RedisConfig {

    @Autowired
    RedisProperties redisProperties;

    @Bean
    public JedisCluster getJedisCluster() {
        //获取redis集群的ip及端口号等相关信息；
        String[] serverArray = redisProperties.getNodes();
        if (null != serverArray) {
            Set<HostAndPort> nodes = new HashSet<>();
            //遍历add到HostAndPort中；
            for (String ipPort : serverArray) {
                String[] ipPortPair = ipPort.split(":");
                nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
            }
            //创建连接池
            GenericObjectPoolConfig poolConfig = getPoolConfig();
            //返回对象
            return new JedisCluster(nodes, redisProperties.getCommandTimeout(), redisProperties.getCommandTimeout(), 3, redisProperties.getPassword(), poolConfig);
        }
        return new JedisCluster(new HashSet<>());
    }

    public GenericObjectPoolConfig getPoolConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(redisProperties.getMaxTotal());
        poolConfig.setMaxIdle(redisProperties.getMaxIdle());
        poolConfig.setMinIdle(redisProperties.getMinIdle());
        poolConfig.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        return poolConfig;
    }
}
